<template>
  <div id="additionalSharePage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <a-space>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
      <a-button type="default" :loading="exportLoading" @click="handleExport">
        <template #icon>
          <ExportOutlined />
        </template>
        導出
      </a-button>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button @click="handleShowDreawer(record)">配置</a-button>
              <a-button @click="handleEdit(record)">修改</a-button>
              <a-button danger @click="handleDelete(record)">刪除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal
      v-model:open="showModalCreate"
      title="新建附加項目類型"
      :footer="null"
    >
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯附加項目
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>

      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>

    <a-drawer
      width="80%"
      :open="showCreateDrawer"
      @close="showCreateDrawer = false"
    >
      <template #title>
        附加項目配置-<a-typography-text type="danger">{{
          subData.name
        }}</a-typography-text>
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleSubCreate">
            <template #icon> <PlusOutlined /></template>添加配置
          </a-button></a-space
        >
      </template>
      <!-- 個別醫師配置列表 -->
      <a-table
        :columns="subColumns"
        :data-source="subData.rules"
        :loading="loading"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'staffType'">
            <a-tag :bordered="false" color="green" v-if="record.staffType == 1"
              >合作</a-tag
            >
            <a-tag
              :bordered="false"
              color="blue"
              v-else-if="record.staffType == 2"
              >員工</a-tag
            >
            <a-tag
              :bordered="false"
              color="orange"
              v-else-if="record.staffType == 0"
              >全部</a-tag
            >
            <a-tag :bordered="false" color="default" v-else>未知</a-tag>
          </template>
          <template v-if="column.dataIndex === 'doctor'">
            <template v-if="record.staffCode">
              {{ record.doctorName }}({{ record.staffCode }})
            </template>
            <template v-else>全部（默認）</template>
          </template>
          <template v-if="column.dataIndex === 'shareType'">
            <a-tag color="orange" v-if="record.shareType === 1">固定金額</a-tag>
            <a-tag color="blue" v-else>比例</a-tag>
          </template>
          <template v-if="column.dataIndex === 'shareValue'">
            <template v-if="record.shareType === 1"
              >$ {{ record.shareValue.toLocaleString() }}</template
            >
            <template v-else> {{ record.shareValue }}%</template>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button @click="handleSubEdit(record)">修改</a-button>
              <a-button danger @click="handleSubDelete(record)">刪除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-drawer>

    <!-- 子新建模態框 -->
    <a-modal v-model:open="showModalSubCreate" :footer="null">
      <template #title>
        添加配置-<a-typography-text type="danger"
          >{{ subData.name }}
        </a-typography-text></template
      >

      <DynamicForm
        ref="createSubFormRef"
        :fieldConfig="createSubFieldConfig"
        @submit="handleSubCreateSubmit"
      />
    </a-modal>

    <!-- 子修改模態框 -->
    <a-modal v-model:open="showModalSubEdit" :footer="null">
      <template #title>
        編輯附加項目-<a-typography-text type="danger">{{
          subData.name
        }}</a-typography-text>
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          {{ subEditFormData.id }}</a-tag
        ></template
      >
      <DynamicForm
        ref="subEditFormRef"
        :fieldConfig="subEditFieldConfig"
        @submit="handleSubEditSubmit"
        :formData="subEditFormData"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  ExportOutlined,
} from "@ant-design/icons-vue";
import { additionalShareApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  getCreteFieldConfig,
  getEditFieldConfig,
  subTableColumns,
  getSubCreteFieldConfig,
  getSubEditFieldConfig,
} from "@/models/addtionalShare";
import { useRouter, useRoute } from "vue-router";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

/******* 頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "附加項目" }];
const columns = tableColumns;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();

// 數據
const tableData = ref([]);
const editRecordId = ref<number>(0); // 當前編輯的附加項目規則ID
const editFormData = reactive<any>({}); // 當前編輯的附加項目規則數據

/******* 數據獲取與初始化 *****************************/
const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await additionalShareApi.getAdditionalTypeList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取附加項目列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};

watchRouteQuery(fetchData);

/******* 附加項目規則操作處理 *****************************/

// 新建
const showModalCreate = ref(false);
const handleCreate = () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreteFieldConfig();
  }
  showModalCreate.value = true;
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    await additionalShareApi.createAdditionalType(data);
    message.success("創建附加項目類型成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建減免方案失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const showModalEdit = ref(false);
const handleEdit = async (record: any) => {
  showModalEdit.value = true;
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = await getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, record);
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    data.type = editFormData.type;
    await additionalShareApi.updateAdditionalType(editRecordId.value, data);
    message.success("修改附加項目成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改附加項目失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 刪除
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除附加項目類型 ${record.name} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await additionalShareApi.deleteAdditionalType(record.id);
        message.success("刪除附加項目類型成功");
        fetchData();
      } catch (error) {
        console.error("刪除附加項目類型失敗:", error);
      }
    },
  });
};

// ==========================subData===========================

//配置
const subColumns = subTableColumns;
const showCreateDrawer = ref(false);
const showModalSubCreate = ref(false);
const createSubFieldConfig = ref<Record<string, any>>({});

const currentType = ref(0);
const subData = reactive<any>({});

const handleShowDreawer = async (record: any) => {
  showCreateDrawer.value = true;
  Object.assign(subData, record);
  currentType.value = record.id;
};

const handleSubCreate = async () => {
  showModalSubCreate.value = true;
  if (Object.keys(createSubFieldConfig.value).length === 0) {
    createSubFieldConfig.value = await getSubCreteFieldConfig();
  }
};

const createSubFormRef = ref();
const handleSubCreateSubmit = async (formData: any) => {
  try {
    const { validDate, ...rest } = formData;
    const createData = {
      ...rest,
      validFrom: validDate[0],
      validTo: validDate[1],
    };
    const { data } = await additionalShareApi.createAdditionalTypeItem(
      createData,
      currentType.value
    );
    message.success("創建配置成功");
    showModalSubCreate.value = false;
    createSubFormRef.value?.resetForm();

    // 將數據添加到tableData中的對應數據的rules中,加載頭部數據
    console.log("data", data);
    subData.rules.unshift(data);
    console.log("subData", subData);
  } catch (error) {
    console.error("創建配置失敗:", error);
  } finally {
    createSubFormRef.value?.resetLoading();
  }
};

// 子項修改
const subEditFormData = reactive<any>({});
const subEditRecordId = ref<number>(0);
const subEditFieldConfig = ref<Record<string, any>>({});
const showModalSubEdit = ref(false);
const handleSubEdit = async (record: any) => {
  // console.log('record', record)
  showModalSubEdit.value = true;
  if (Object.keys(editFieldConfig.value).length === 0) {
    subEditFieldConfig.value = await getSubEditFieldConfig();
  }
  subEditRecordId.value = Number(record.id);
  // 初始化編輯表單數據
  record.validDate = [record.validFrom, record.validTo];
  Object.assign(subEditFormData, record);
  // console.log("subEditFormData", subEditFormData);
};

const subEditFormRef = ref();
const handleSubEditSubmit = async (formData: any) => {
  try {
    const { validDate, ...rest } = formData;
    const editData = {
      ...rest,
      validFrom: validDate[0],
      validTo: validDate[1],
    };
    const { data } = await additionalShareApi.updateAdditionalTypeItem(
      subEditRecordId.value,
      currentType.value,
      editData
    );
    message.success("修改附加項目成功");
    // 修改後的數據
    subData.rules = subData.rules.map((item: any) => {
      if (item.id === subEditRecordId.value) {
        return {
          ...item,
          ...data,
        };
      }
      return item;
    });
    showModalSubEdit.value = false;
    // fetchData(route.query);
  } catch (error) {
    console.error("修改附加項目失敗", error);
  } finally {
    subEditFormRef.value?.resetLoading();
  }
};

// 刪除
const handleSubDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除附加項目配置項 #${record.id} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await additionalShareApi.deleteAdditionalTypeItem(
          record.id,
          currentType.value
        );
        //移除配置
        subData.rules = subData.rules.filter(
          (item: any) => item.id !== record.id
        );
        message.success("刪除配置成功");
        fetchData();
      } catch (error) {
        console.error("刪除配置失敗:", error);
      }
    },
  });
};

const exportLoading = ref(false);
// 導出
const handleExport = async () => {
  try {
    exportLoading.value = true;
    await additionalShareApi.exportAdditionalShareList();
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped></style>
